function gadget:GetInfo()
return {
		name = "gather.lua",
		desc = "adds gather command",
		author = "tomr13",
		date = "10/11/2011",
		license = "public domain",
		layer = 1,
		enabled = true,
}
end

local resourceTypes = {}
 resourceTypes[UnitDefNames["wreckage"].id]= {
 mineRange=60,
}

local workerTypes={}
workerTypes[UnitDefNames["gatherer"].id]={
  capacity=5,
  gatherTime=1,
}

local hqTypes={}

hqTypes[UnitDefNames["simplefactory"].id]={
  returnRange=60
}
--endconfig

local Resources = {
	[UnitDefNames.wreckage.id] = "wreckage",
}

local Gatherers = {
	[UnitDefNames.gatherer.id] = "gatherer",
}
local CMD_GATHER = 33634

local echo = Spring.Echo

if not GG.attUnits then
	GG.attUnits = {}
end

local hqs = {}

local workers={}

Gather = {
		id=CMD_GATHER,
		type=CMDTYPE.ICON,
			name="Gather",
			texture="&.9x.9&bitmaps/icons/blank.tif&bitmaps/icons/burrow.png",
			tooltip="Gathers wreckage.",
			action="gather"
		}
if (not gadgetHandler:IsSyncedCode()) then 
 return false
end

function GatherResourcesInRange(unitID, teamID, maxDistance)
--if (workers2[unitID] != true)
local allUnits = Spring.GetAllUnits()
	for _, unitID2 in ipairs(allUnits) do
		local def =  Spring.GetUnitDefID(unitID2) 
		if (resourceTypes[def]) then
			local seperation=Spring.GetUnitSeparation(unitID2, unitID)
			if(seperation<200) then
				Spring.DestroyUnit(unitID2,true,false)
				echo("Unit Def " .. unitID2)
				workers[unitID] = true
				return
			end
			
		end
--	end
	end
	--Spring.DestroyUnit(unitID,true,false)
end

function gadget:GameFrame(frame)    
	if frame % (30) == 4 then 
		for k, v in pairs(workers) do
			if(v == true) then
				for k2, v2 in pairs(hqs) do
					local def =  Spring.GetUnitDefID(k)
					local seperation=Spring.GetUnitSeparation(k, k2)
					if(seperation<200) then
						--echo(v2 .. "")
						Spring.AddTeamResource(v2, "metal", 100)
						workers[k] = false
						return
					end
				end
			end
		end
	end
 end

function gadget:CommandFallback(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
 if (cmdID~=CMD_GATHER) then
  return false
 end
 if(not workerTypes[unitDefID]) then
  return true, true 
 end
local a = GatherResourcesInRange(unitID, teamID, 100000)
end



function gadget:UnitCreated(unitID, unitDefID, unitTeam)
  if (workerTypes[unitDefID]) then
   Spring.InsertUnitCmdDesc(unitID, Gather)
   table.insert(workers, unitID, false)
  end
  if (hqTypes[unitDefID]) then
	table.insert(hqs, unitID, unitTeam)
  end
end

function gadget:Initialize()
 gadgetHandler:RegisterCMDID(CMD_GATHER)
end